package cn.com.hp.feature.service.impl;

import cn.com.hp.feature.service.IWechatService;
import cn.com.hp.feature.util.OkHttpUtil;
import cn.com.hp.feature.util.RequestUtils;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author: hjz
 * @since: 2022/9/7
 * @description:
 */
@Service
@Slf4j
public class WechatServiceImpl implements IWechatService {
    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;

    @Value("${wechat.wechatUrl}")
    private String wechatUrl;

    @Autowired
    private RequestUtils requestUtils;

    @Override
    public String getWechatOpenId(String code) {
        Map<String, String> paramMap = new HashMap<>(16);
        paramMap.put("appid", appid);
        paramMap.put("secret", secret);
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        String url = wechatUrl + "/sns/jscode2session";

        String respStr = OkHttpUtil.get(url, null, paramMap);
        Map<String, String> resp = JSON.parseObject(respStr, Map.class);
        if (Objects.isNull(resp)) {
            return null;
        }
        return resp.get("openid");
    }
}
